Knockout validation - to match starts with specific characters - javascript

I have to validate if an ID starts with a specific set of characters, followed by alphanumeric values. I am using knockout validation.
I have the code here,
var value_id = ko.observable('').extend({
minLength: 18,
maxLength: 18,
pattern: {
params: '/^(xyz34|xyz12)((?=.*[a-zA-Z])(?=.*[0-9])){13}/g',
message: 'Please provide a valid ID.'
},
required: {
message: 'Please enter a ID.',
params: true
}
});
The same pattern is working fine in online regex tester.
Any suggestion would be helpful.

Related

How to verify email in ReactJS?

I'm trying to remove the default email verification and add my own email verification to a signup form in ReactJS. Initially, I would like to verify that the email address entered contains #. For this, I put together the code below, however, it is not working.
if (!form.email.value.includes('#')) {
setWarning({
show: true,
message: 'Please provide a valid email address.'
})
setTimeout(() => {
setWarning({
show: false,
message: ''
})
}, 3000)
return
}
In the future, I would also like to use regEx to validate the password, as I'm currently only validating the number of characters, but I still haven't learned how to do that in ReactJS. I would like my password to have at least 1 uppercase letter, 1 lowercase letter, 1 number and no symbol type. Currently, my code looks like this:
if (form.password.length < 6) {
setWarning({
show: true,
message: 'The password must be at least 6 characters long.'
})
setTimeout(() => {
setWarning({
show: false,
message: ''
})
}, 3000)
return
}
Well first of all I may advice you to post in this Stack Overflow in English. If you want you can head to "Stack Overflow em Português" (https://pt.stackoverflow.com/) where the community is portuguese :)
Regarding your first question, you really shouldn't verify the e-mail using "ifs". Well looking at your code if, let's say, someone enters "um_email#extra#mail.pt" it will be allowed. I strongly sugest you to use regex for it. To ensure that you are using the correct variable I added an console log. Your code would look something like this:
console.log(form.email.value);
let emailReg = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w\w+)+$/;
if (emailReg.test(form.email.value) === false) {
setWarning({
show: true,
message: 'Informe um e-mail válido.'
})
setTimeout(() => {
setWarning({
show: false,
message: ''
})
}, 3000)
return
}
At you're second question, well Stack Overflow is not the type of "I need this, can someone do it for me?". You first need to look arround and try things for yourself, trying diferent regex and how they work. But yeah, regarding you being a new contributor I will try to help you with this one.
// (?=.{6,}) - at least 6 characters or more
// (?=.*\d) - at least 1 decimal
// (?=.*[a-z]) - at least 1 lower case
// (?=.*[A-Z]) - at least 1 upper case
// (?!.*\W) - no special character
let passwordReg = /^(?=.{6,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\W).*$/;
if (passwordReg.test(form.password) === false) {
setWarning({
show: true,
message: 'A senha não é válida.'
})
setTimeout(() => {
setWarning({
show: false,
message: ''
})
}, 3000)
return
}
Hope I could help you. :)
Ps.:If this answers your question, please mark it as correct :)

How to add this UK registration validation to jquery?

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"
},
}
});
}

JQuery form validations plugin regex (pattern method) problems

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.

Regex in validate.js not working as expected

I have the below rules and using validate.js but regex does not seem to work. Below is my code.
Condition given : Check if string has at least one capital letter, at least one symbol and at least one number
password: {
presence: {
message: '^Please enter a password'
},
length: {
minimum: 5,
message: '^Your password must be at least 6 characters'
},
format: {
pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[\w~##$%^&+=`|{}:;!.?\""()\[\]-]{1,}$/,
message:
'^Must contain a capital, lowercase, number and a special character!'
}
}

jQuery Validate with input arrays

The following code results in the following error:
SyntaxError: Unexpected token ).
Any ideas?
$("#signupForm").validate({
rules: {
'entry[first_name]': "required",
'answers[985575][answer]': "required",
'answers[985574][answer]': {
required: true,
phoneUS: true
},
'entry[email]': {
required: true,
email: true
}
}});
The phoneUS is not a standard, built-in rule. So unless you have defined it, it won't work. As explained in the documentation you need to define it. They provide the following method that you need to include in order to define the phoneUS rule:
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
phone_number = phone_number.replace(/\s+/g, "");
return this.optional(element) || phone_number.length > 9 &&
phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
}, "Please specify a valid phone number");
And here's a working live demo.

Categories

Resources