In this project I have the following jquery code to validate a form. It works fine, but i'd like it to be more specific by implementing a more thorough validation for UK reg plates.
My javascript code is:
function ValidateSspcpForm()
{
$('#SspcpForm').validate({
rules: {
'sspcp[reg]': {
required: true,
rangelength: [2, 8],
},
messages: {
'sspcp[reg]': {
required: "Your car's registration is required in advance, Please input one here.",
rangelength: "The registration number must be between 2 and 7 characters in length"
},
}
});
}
The method I want to implement is this, it seems to cover everything for UK plates which is perfect for my use case:
(^[A-Z]{2}[0-9]{2}\s?[A-Z]{3}$)|(^[A-Z][0-9]{1,3}[A-Z]{3}$)|(^[A-Z]{3}[0-9]{1,3}[A-Z]$)|(^[0-9]{1,4}[A-Z]{1,2}$)|(^[0-9]{1,3}[A-Z]{1,3}$)|(^[A-Z]{1,2}[0-9]{1,4}$)|(^[A-Z]{1,3}[0-9]{1,3}$)
Any help or ideas would be much appreciated!
Found it. Definitely appears to be quite simple. I'm new to JavaScript, so wasn't aware it would let you outside of the validate method. For anyone else searching, this is how you would implement UK registration plate validation with jquery.validate:
function ValidateSspcpForm()
{
$.validator.addMethod('Registration', function(value){
return /^(^[A-Z]{2}[0-9]{2}\s?[A-Z]{3}$)|(^[A-Z][0-9]{1,3}[A-Z]{3}$)|(^[A-Z]{3}[0-9]{1,3}[A-Z]$)|(^[0-9]{1,4}[A-Z]{1,2}$)|(^[0-9]{1,3}[A-Z]{1,3}$)|(^[A-Z]{1,2}[0-9]{1,4}$)|(^[A-Z]{1,3}[0-9]{1,3}$)|(^[A-Z]{1,3}[0-9]{1,4}$)|(^[0-9]{3}[DX]{1}[0-9]{3}$)/.test(value);
}, 'reg validation has failed');
$('#SspcpForm').validate({
rules: {
'sspcp[reg]': {
required: true,
rangelength: [2, 8],
Registration: true
},
},
messages: {
'sspcp[reg]': {
required: "Your car's registration is required in advance, Please input one here.",
Registration: "This registration number is not a recognised UK plate"
},
}
});
}
Related
this is my first post ever on stack overflow!
I've been trying to use the jquery validator plugin to validate my register form on php without submitting it (i already have server-side validations). Well, i don't know much about js (for now) but i'm trying to use jquery validation from this plugin https://jqueryvalidation.org/
I'm also using the additional-methods.js (pattern included) which gives you more validation methods.
Let me explain my situation... I'm using regex on php to validate my html forms and it works like a charm. When i tried to use the same regex for jquery it'd throw and error (i already have some basic code js and it works).
I tried a lot of regex formats and nothing works, i don't know what i'm doing wrong. I also tried to escape the code and it doesn't throw errors but it still doesn't work.
I'm getting "invalid format" all the time and i can't seem to understand why is it not working.
All the regex formats i've found on the internet don't work, it's crazy, maybe you can help me.
This is the pattern i'm actually using to validate the nombre (name) input in php: /^\pL+(?>[ ']\pL+)*$/u
*Also I've copied the patterns method inside my local js and removed the additional-methods cdn from my .php but it's the same.
** Ignore the [A-Z] thingy, i've been trying a lot of things, none of them work :(
Here my local.js
$.validator.setDefaults({
errorClass: 'text-danger position-absolute ml-1',
highlight: function
(element) {
$(element)
.closest('.form-control')
.addClass('is-invalid');
},
unhighlight: function (element) {
$(element)
.closest('.form-control')
.removeClass('is-invalid');
},
errorPlacement: function (error, element) {
if (element.prop('type') === 'checkbox') {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
$.validator.addMethod("pattern", function (value, element, param) {
if (this.optional(element)) {
return true;
}
if (typeof param === "string") {
param = new RegExp("^(?:" + param + ")$");
}
return param.test(value);
}, "Invalid format.");
$("#reg_form").validate({
debug: true,
rules: {
nombre: {
required: true,
pattern: [A-Z]
},
apellido: {
required: true,
lettersonly: true
},
email: {
required: true,
email: true,
},
password: {
required: true,
strongPassword: true
},
cpassword: {
required: true,
equalTo: '#password'
}
},
messages: {
nombre: {
required: 'Requerido',
pattern: 'Formato inválido',
max: 'Muy largo'
},
apellido: {
required: 'Requerido',
pattern: 'Formato inválido',
max: 'Muy largo'
},
email: {
required: 'Please enter an email address.',
email: 'Por favor ingresa un email <em>válido</em>.',
},
password: {
required: true
}
}
});
You may have a minor oversight, change your pattern implementation to -
nombre: {
required: true,
pattern: "^[A-z\s]+$"
},
your pattern needs to be a string for it to be implemented. Secondly while \pL does work well to get any letter form any language, but not all programming languages have it implemented. (look here for what you can do in java script) You are better off just adding in the few extra letters you expect to encounter in the regex.
I have a page similar to the below given diagram,
The page has multiple sections (User Information, Account Information etc;) as well as common controls (like subject textbox, date textbox etc)
When the user clicks on Add button in user information section, it has to validate the associated controls
When the user clicks on the Submit button in the top, the subject textbox and the table should be validated for required data.
How can I achieve this?
I am able to validate the user section but not sure how to proceed with global validation on the page.
TypeScript:
class Validation {
static FormTrackingId = '#FormTracking';
private static ApplyRules() {
$(Component.SelectId).rules("add", {
required: true,
messages: {
required: "Name is required."
}
});
$(Component.TextBoxNumberId).rules("add", {
required: true,
messages: {
required: "Number is required."
}
});
$(Component.TextAreaNotesId).rules("add", {
maxlength: 10,
messages: {
maxlength: jQuery.validator.format("The maximum allowed length of note(s) is {0} characters.")
}
});
}
public static IsValid(): boolean{
$(Validation.FormTrackingId).validate();
Validation.ApplyRules();
return $(Validation.FormTrackingId).valid();
}
}
Any suggestion on how to handle this scenario will be greatly appreciated. Thanks.
I'm using the FormValidation plugin in Bootstrap and am loving it, except I can't figure out one thing. I have a form with an "other" check box. If you check "other", I want an explanation typed into another field. I've been all over the website (formvalidation.io), but I'm not finding an answer. Unfortunately, I know just enough JS to be dangerous.
Here's the code for the validator I'm using on the check boxes.
'work_type[]': {
validators: {
choice: {
min: 1,
message: 'Please choose at least one work type.'
}
}
}
There's another field called "other_work" that I would like to require a string in if work_type has a value of "Other Work".
For anyone trying to figure this out check out callback functions
You declare your own function something like this:
function optionOtherValidator(value) {
if ($('#amountOther input').is(':checked');) {
return /^\w+$/.test(value);
}
return true;
},
Then in your fields array you declare it as a callback:
fields: {
optionOther: {
validators: {
callback: {
message: 'Please specify a value for other',
callback: optionOtherValidator
}
}
}
...
This problem, i am sure is very trivial but i am not able to get past it.
My form is not getting validated using jquery validate.
$(document).ready(function () {
$("#loginForm").validate({
rules: {
email: "required",
passwd: "required",
email:{
minlength: 10
}
},
messages: {
email: "Please enter your email",
passwd: "Please enter your passwd",
email:{
minlength: "Minlength has to be 10"
}
},
submitHandler: function(form) {
$("#pp").text("right");
form.submit();
}
});
})
No console errors. I have following
name, passwd are name, id of the fields i am trying to validate and loginForm is id of form. The problem is i don't see the error messages when i pass invalid input. Going through debug mode, i don't see the stack reaching inside validate function ever although an alert inside ready function before validate is called.
You did not show your HTML markup, so this answer assumes you correctly named your input elements.
In your code, you're specifying email twice...
rules: {
email: "required",
passwd: "required",
email:{ // <- duplicate
minlength: 10
}
},
If you need to specify multiple rules for one field, then specify the field once and list the rules inside...
rules: {
email: {
required: true,
minlength: 10
},
passwd: "required"
},
Your messages option has the same problem.
Working DEMO: http://jsfiddle.net/4937t/
I am using a select method in form and when I click on submit method without filing the form, various errors are shown which I have included in validate methods, like first name required, email required, etc.
So the problem is when I start entering the first name, the error disappears. But the same is not happening in case of select method. When I select certain options there, the error still remains saying, select at least one option. This error goes away when I click submit button. But I want this error to go away when I select at least one option, like in the case of first name when I start typing, the error goes away.
I have included my validation methods in $(document).ready(function()
Any help will be appreciated.
The following is the code snippet:
var newusercontainer = $('#newUsererrorcontainer');
var newuservalidator = $("#newUserForm").validate({
submitHandler: function(form) {
registerUser();
},
errorContainer: newusercontainer,
errorLabelContainer: $("ul", newusercontainer),
wrapper: 'li',
meta: "validate",
rules: {
newUserFirstName: {
required:true,
maxlength:50,
},
sector: {
required: true,
},
},
messages: {
newUserFirstName: {
required: "The First name field is required.",
maxlength: "Please enter with in 60 characters"
},
sector: {
required: "The Sector field is required.",
},
}
});