Reputation: 1793
I'm new to programming. I'm trying to validate a form. I did it with php (I'm using Codeigniter) and had no problem with it, works fine.
When it comes to jquery I'm having trouble. For example, for username, it should appear an ok icon if the input validates. For that I've this:
var FormValidation = function () {
var handleValidation2 = function() {
// for more info visit the official plugin documentation:
// http://docs.jquery.com/Plugins/Validation
var form2 = $('#form-val');
var error2 = $('.alert-error', form2);
var success2 = $('.alert-success', form2);
//IMPORTANT: update CKEDITOR textarea with actual content before submit
form2.on('submit', function() {
for(var instanceName in CKEDITOR.instances) {
CKEDITOR.instances[instanceName].updateElement();
}
})
form2.validate({
errorElement: 'span', //default input error message container
errorClass: 'help-inline', // default input error message class
focusInvalid: false, // do not focus the last invalid input
ignore: "",
rules: {
username: {
minlength: 2,
maxlength: 15,
regex: "^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$",
required: true
},
name: {
minlength: 2,
maxlength: 50,
// regex: ,
required: true
},
lastname: {
minlength: 2,
maxlength: 50,
required: true
},
gender: {
required: true
},
date_born: {
required: true
},
email: {
required: true,
email: true
},
status: {
required: true
},
member_id: {
minlength: 5,
},
documentType_id: {
required: true
},
documentn: {
required: true,
minlength: 2
},
address_street: {
required: true
},
address_number: {
required: true
},
address_floor: {
required: false
},
zipcode: {
required: true
},
city: {
required: true
},
state: {
required: true
},
country_id: {
required: true
},
phone: {
required: true
},
cellphoneNumber: {
required: true
},
cellCompany: {
required: true
},
cellbrand: {
required: true
},
marital_status: {
required: true
},
sons: {
required: true
},
},
messages: { // custom messages for radio buttons and checkboxes
username: {
required: "Este campo es requerido",
minlength: "El nombre de usuario debe tener como mínimo 2 caracteres",
maxlength: "El nombre de usuario debe tener como máximo 15 caracteres",
},
membership: {
required: "Please select a Membership type"
},
service: {
required: "Please select at least 2 types of Service",
minlength: jQuery.format("Please select at least {0} types of Service")
}
},
errorPlacement: function (error, element) { // render error placement for each input type
if (element.attr("name") == "education") { // for chosen elements, need to insert the error after the chosen container
error.insertAfter("#form_2_education_chzn");
} else if (element.attr("name") == "membership") { // for uniform radio buttons, insert the after the given container
error.addClass("no-left-padding").insertAfter("#form_2_membership_error");
} else if (element.attr("name") == "editor1" || element.attr("name") == "editor2") { // for wysiwyg editors
error.insertAfter($(element.attr('data-error-container')));
} else if (element.attr("name") == "service") { // for uniform checkboxes, insert the after the given container
error.addClass("no-left-padding").insertAfter("#form_2_service_error");
} else {
error.insertAfter(element); // for other inputs, just perform default behavior
}
},
invalidHandler: function (event, validator) { //display error alert on form submit
success2.hide();
error2.show();
App.scrollTo(error2, -200);
},
highlight: function (element) { // hightlight error inputs
$(element)
.closest('.help-inline').removeClass('ok'); // display OK icon
$(element)
.closest('.control-group').removeClass('success').addClass('error'); // set error class to the control group
},
unhighlight: function (element) { // revert the change done by hightlight
$(element)
.closest('.control-group').removeClass('error'); // set error class to the control group
},
success: function (label) {
if (label.attr("for") == "service" || label.attr("for") == "membership") { // for checkboxes and radio buttons, no need to show OK icon
label
.closest('.control-group').removeClass('error').addClass('success');
label.remove(); // remove error label here
} else { // display success icon for other inputs
label
.addClass('valid').addClass('help-inline ok') // mark the current input as valid and display OK icon
.closest('.control-group').removeClass('error').addClass('success'); // set success class to the control group
}
},
submitHandler: function (form) {
success2.show();
error2.hide();
}
});
$('#form-val').select2({
placeholder: "Select an Option",
allowClear: true
});
//apply validation on chosen dropdown value change, this only needed for chosen dropdown integration.
$('.chosen, .chosen-with-diselect', form2).change(function () {
form2.validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
});
//apply validation on select2 dropdown value change, this only needed for chosen dropdown integration.
$('.select2', form2).change(function () {
form2.validate().element($(this)); //revalidate the chosen dropdown value and show error or success message for the input
});
}
return {
main function to initiate the module
init: function () {
handleValidation2();
}
};
}();
That is full code, not yet finished making changes. The thing is that erros appears if input is less than 2 characters or bigger than 15, but when it's a correct input, icon ok doesn't appear and have the following error when inspecting it:
Uncaught TypeError: Cannot call method 'call' of undefined
If i erase the rule "regex" icon ok appears. But as you can see in the snippet, with that field it doesn't work fine.
What can the problem be? thnx in advance.
Upvotes: 0
Views: 1845
Reputation: 780974
If you want to match a regular expression without writing a custom method (as in Hayzeus's) answer, load the jquery-validate additional methods:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>
Then you can use the pattern
validation method:
username: {
minlength: 2,
maxlength: 15,
pattern: "[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*",
required: true
},
The method automatically wraps the pattern with ^
and $
, so you don't need them in your regexp.
Upvotes: 2
Reputation: 63
You can't simply provide a regex string in your rules. You need to add a custom method to the validator.
Something like this:
$.validator.addMethod("regex", function(value, element) {
var regex = /^[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*$/
return regex.test(value);
}, "Invalid Name");
Then in your rule:
username: {
minlength: 2,
maxlength: 15,
regex: true,
required: true
}
Upvotes: 1