Validate specific format without using "-" to split the string - javascript

Hi i need to validate a string before sending my form, the format must be
LLLL999999XXX
Where L is any letter
9 is any number
X is any letter or number.
I figure out how to do this using - to split, the problem is that my users use to enter this value with out the - , so its going to be strage if i ask for a - in the format. (in this moment i ask , pls enter format LLLL-999999-XXX wich is no good.)
How can i validate this, without using - , any ideas? sorry im newbie at javascript
<script language="JavaScript">
function RFC(cual)
{
mensaje = "pls enter this format LLLL-999999-XXX"
pat = /[a-z]|[A-Z]/
pat2 = /[a-z]|[A-Z]|[0-9]/
val = cual.split("-")
if (val.length == 3){
if(val[0].length == 4){
if(!comp(val[0],pat)){
alert( mensaje)
return false
}
}
if(val[1].length == 6){
if(isNaN(val[1])){
alert('no es un numero')
return false
}
}
if(val[2].length == 3){
if(!comp(val[2],pat2)){
alert(mensaje)
return false
}
}
else{
alert(mensaje)
return false
}
}
else{
alert(mensaje)
return false
}
return true
}
function comp(cual,pa){
for(m=0;m<cual.length;m++){
if(!pa.test(cual.charAt(m))){
return false
break
}
}
return true
}
</script>

You could just use the regex as below:
/^[a-z]{4}[0-9]{6}[a-z0-9]{3}$/i
If you want - as optional:
/^[a-z]{4}-?[0-9]{6}-?[a-z0-9]{3}$/i

UPDATED:
var input = "LLLL999999XXX";
var pattern = /^[a-zA-Z]{4}\d{6}[a-zA-Z0-9]{3}$/;
if( input.match(pattern) ){
alert("true");
}else{
alert("false");
}
See the working code at:
JsFiddle

Related

check if input form value (int) is less than expected

My question is about validating a form. I am doing a validation of two fields, one of them receives the value in decimal, example ($ 500.00), is already with mask.
In this field that receives the value, it can not be less than 300.00.
If it is smaller 300.00, a message will appear saying the value has to be greater than 300.00.
Summary: The validation checks that it is empty, but does not check if the (number) int is less than $ 300
I'm using it this way (there's more code, in short):
function valid_simulation(form1) {
if (form1.valor.value == ' ') {
alert("value is not valid");
return false;
}
if (form1.valor.value <= 300) {
alert("value is not valid");
return false;
}
}
Thanks for any help.
Your basic concept is correct: set the message when the if statement test is falsy. Something like the following:
function showFormError(message) {
$("#alertBox").text(message)
}
if (isInvalid) { showFormError("We have a problem.") }
If the dollar mark is the issue, You can split it and validate.
var userInput = $("#inputData").val();
if(userInput.includes("$")) {
var splitArray = userInput.split("$");
if (typeof splitArray[1] && parseFloat(splitArray[1]) < 300){
alert("Amount Not valid");
}
}

What is wrong with this number script?

I'm very new to JavaScript and I want to do an input check.
Here is my script:
function checkInp()
{
var x=document.forms["myForm"]["num"].value; // Get the value
if (isNaN(x))
{
alert("Not a number!"); // Check if the input is a number
return false;
}
var valuex=document.forms["myForm"]["num"].value; // Get the value, i don't know if i have to re-write this variable, if no, please comment.
Number(valuex); // Make the input a number
if (valuex.value > 480) {
alert("Too high!"); // See if the number is greater than 480. If yes, say that, if not, return normally.
return false;
}
else {
return;
}
}
I don't know what happens, but the script doesn't work since I added the second part (to check if the number is greater than 480).
Please help me, with full example if possible.
If i'm not wrong, i thnk you need just to do like this:
If(valuex > 480)..
The way I'll doing it:
Document selectorQuery is more understandable
Dont get the value multiple time
Use ParseInt to transform your var on number
Don't forget to return true if success
Code:
function checkInp() {
var x = document.querySelector('input[name="num"]').value;
if (isNaN(x)) {
alert("Must be a number");
return false
} else if (x > 480) {
alert("Must be under 480");
return false
}
return true
}

regex expression in javascript not working as expected

we are trying to find if the given string is a valid indian mobile number or not
valid indian mobile number
starts with 7 or 8 or 9
followed by 9 same or different numbers
here is my JavaScript for matching it, but unfortunately it returns false even when number is correct
var mobile_number = $('#number').val();
var mobile_regex = new RegExp('/^[789]\d{9}$/');
if(mobile_regex.test(mobile_number) == false) {
console.log("not valid");
} else {
console.log("valid");
}
Your code has two problems. If you're using a RegExp object, you don't need / characters, and the \ character needs to be escaped.
This would work:
var mobile_regex = new RegExp("^[789]\\d{9}");
Alternatively, if you want to use the other format, this would work:
if(!mobile_number.match(/^[789]\d{9}/)) {
console.log("not valid");
} else {
console.log("valid");
}
You can try this
var mobile_number = $('#number').val();
var mobile_regex = new Regex("^[7-9][0-9]{9}$")
if(mobile_regex.test(mobile_number) == false) {
console.log("not valid");
} else {
console.log("valid");
}

Can't get javascript to popup alert for leap year

<button onclick="isleap(1992)">Try it</button>​
function isleap(year);
{
var yr=document.getElementById("year").value;
if ((parseInt(yr)%4) == 0)
{
if (parseInt(yr)%100 == 0)
{
if (parseInt(yr)%400 != 0)
{
alert("Not Leap");
return "false";
}
if (parseInt(yr)%400 == 0)
{
alert("Leap");
return "true";
}
}
if (parseInt(yr)%100 != 0)
{
alert("Leap");
return "true";
}
}
if ((parseInt(yr)%4) != 0)
{
alert("Not Leap");
return "false";
}
}
​
http://jsfiddle.net/kcyCd/
Having problems figuring out how to get the code to popup the alert box with the answer to the leap year.
A simple isLeapYear function is:
function isLeapYear(year) {
var d = new Date(year, 1, 29);
return d.getMonth() == 1;
}
It just sees if 29 February occurs in the given year. You should be able to do:
function isLeapYear2(year) {
return !!Date.parse(year + '-02-29');
}
on the basis that parsing an invalid date should return NaN, which type-converts to false, but not all browsers correctly implement Date.parse. e.g.
isLeapYear2('2001'); // false in Firefox, true in IE
<button onclick="alert(isleap(1992));">Try it</button>
If you alert the value returned from the isleap function it should work. I'm not guaranteeing the answer that pops up will be correct though.
Your fiddle doesn't work because you've kept the default jsfiddle setting that places your JS in an onload handler, which means your function isn't global and isn't accessible from the inline onclick attribute - this should be changed in the drop-down on the left to one of the "no wrap" settings. Also, the first thing the function would do if called is try to read the value from an element with id "year" and you have no such element. You currently ignore the year parameter.
Having said that, your function is way more complicated than it needs to be. You can greatly simplify your code by doing the parseInt() once at the beginning, then do whatever it is you need to do if the value being tested isn't an integer, and then you can do the leap year test in just one line.
Also, if you're using parseInt() on user input you must specify a radix as the second parameter if you want to avoid obscure bugs due to input starting with a leading zero being treated as octal. So parseInt(year, 10).
Finally, why return strings "true" and "false"? Wouldn't it make more sense to return actual booleans so that you can call your function as:
if (isleap(1992)) {
// do something
}
Anyway, here's a short version:
function isleap(year) {
year = parseInt(year,10);
if (isNaN(year)) {
alert("Not a number");
return false;
}
if (year%4===0 && (year%100!=0 || year%400===0)) {
alert("Leap");
return true;
} else {
alert("Not leap");
return false;
}
}
Demo: http://jsfiddle.net/kcyCd/1/
If you didn't need to display the alert you could make it shorter still:
function isleap(year) {
year = parseInt(year,10);
if (isNaN(year)) {
alert("Not a number");
return false;
}
return (year%4===0 && (year%100!=0 || year%400===0));
}
And obviously it would be a one-liner if you didn't need to test for invalid values.
You're passing a value into the function, and then looking for a different value in the DOM that doesn't exist.
Also, the code is hard to follow since you merged true/false conditionals, and you're using a string instead of a boolean - which is bad, because if(isleap(1992)) will always be true in your code.
Simplified:
function isleap(year)
{
if(year % 4 == 0 || (year % 100 == 0 && year % 400 == 0)){
return true;
}
return false;
}

jQuery validate phone number with with RegEx

I have a simple ajax form and I'm trying to validate that it
has a value
that value is a 10 digit number
I'm trying to use RegEx to do so. Here is what I have so far.
var reg = new RegExp("/[0-9]{10}/");
$("#call_form").bind("submit", function() {
if ($("#call_number").val().length < 1 && reg.test($("#call_number").val())) {
$("#call_error").show();
return false;
}
});
I know the problem has to do witht he RegExp as if I remove this portion of the code it validates that the box has a value.
EDIT: Here is the final regex I'm using
var regEx = new RegExp("/[0-9]/");
$("#call_form").bind("submit", function() {
if ($("#call_number").val().length != 10 && !$("#call_number").val().match(regEx)) {
$("#call_error").show();
$.fancybox.resize();
return false;
}
});
EDIT 2
Using the suggestions here is what i'm usign which allows spaces and dashes that then get stripped on check
$("#call_form").bind("submit", function() {
var Phone = $("#call_number").val().replace(/\D+/g,'');
if (Phone.length != 10) {
$("#call_error").show();
$.fancybox.resize();
return false;
}
});
Here is what I use - its simple, just posting if someone is searching for the same.
var a = PHONE_FROM_FIELD;
var filter = /^[0-9-+]+$/;
if (filter.test(a)) {
return true;
}
else {
return false;
}
Cheers!
Your regex works fine for me... you could shorten it to just /[0-9]{10}/.
Your problem is here:
$("#call_number").val().length < 1. If the number is 10 characters long, it will never be less than 1, no?
You probably meant something like this:
$("#call_number").val().length === 10
No one has said what was wrong with your original effort - it's the slashes (/). When calling RegExp as a constructor, you don't need the slashes (which are a token to indicate a regular expression litteral), e.g.:
var re = /\w+/i;
is equivalent to:
var re = new RegExp('\\w+','i');
Note that you have to quote backslashes for special characters.
One last thing - allow spaces in the number. You might remove them before testing or storing though. Users find it much easier to read numbers in blocks of 3 or 4 digits, e.g.
1234 871 098 is easier to read than 1234871098.
something like this:
var regEx = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
$("#call_form").bind("submit", function() {
var val = $("#call_number").val();
if (!val.match(regEx)) {
$("#call_error").show();
return false;
}
});
function validate_Phone_Number() {
var number = $('field_Id').val();
var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
if (filter.test(number)) {
return true;
}
else {
return false;
}
}
use same validation with keypress and keyup using jquery , working for me
jquery code
const goodColor = "#0C6";
const badColor = "#FF0000";
const $mobile_validation = $('#mobile_validation');
$('#mobile').on('keyup keypress', function(e) {
if (e.which == 46 || e.which == 45 || e.which < 48 || e.which > 57) {
event.preventDefault();
}
if(this.value.length !=10 ){
$mobile_validation.text("Please enter 10 digit mobile number ");
$mobile_validation.css("color", badColor);
}
if(this.value.length ===10 ){
$mobile_validation.text("Good!");
$mobile_validation.css("color", goodColor);
}
});
html code
<input type="text" id="mobile" class="form-control" name="telephone" maxlength="10">
<span id="mobile_validation"></span>
// check phone number validation
function validatePhoneNumber(number)
{
count=number.length;
if(number[0]!=" " && number[0]!="-" && number[count-1]!=" " && number[count-1]!="-")
{
temp=number.replace(" ", "");
temp=temp.replace("-", "");
if($.isNumeric(temp))
{
if(temp.length>=7 && temp.length<=12)
{
flag=1;
for(i=1;i<count;i++)
{
if(number[i]=="-" || number[i]==" ")
{
if(number[i-1]=="-" || number[i-1]==" " || number[i+1]=="-" || number[i+1]==" ")
{
flag=0;
}
}
}
if(flag==1)
{
valid=1;
}
else
{
valid=0;
}
}
else
{
valid=0;
}
}
else
{
valid=0;
}
}
else
{
valid=0;
}
return valid;
}

Categories

Resources