How do I validate this regex in JavaScript? - javascript

<input id="phone" name="phone" placeholder="(XXX)XXX-XXXX" type="tel"
pattern="^(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}$" required="true"/>
How can I validate if that pattern is used in JavaScript for browsers that don't support the pattern attribute?
Thank you for your input -- I've tried doing several options below, but I can't seem to get anything to trace out as "true" -- the RegExp works in the HTML pattern field for FireFox and Chrome. But it's always returning false when I'm trying to utilize it with javaScript?
http://pastebin.com/M0Pdn2Z3

There are a number of polyfills that will enable this in older browsers:
nwxforms, no dependencies
HTML5 Form Shim, requires jQuery
h5Validate, also requires jQuery
I'd recommend polyfilling -- this doesn't change the behavior for modern browsers but emulates it in old ones. (An aside: the Modernizr polyfills list is fantastic.)
You could also write it yourself; some other answers show how that's done.

Create an onchange event that reads the pattern attribute and runs it against the value.
// Only bind event if we need to
if(!('pattern' in document.createElement('input'))){
// Bind the event
document.getElementById('phone').addEventListener('change', function(){
// Get the regex and value then test it
var regex = new RegExp(this.pattern),
val = this.value,
valid = regex.test(val);
// Is it valid?
if(!valid){
// Do something when it's not
}
});
}

You should validate when submitting the form, or losing focus from the input.
If you use jQuery, this will work for all elements with pattern attribute:
$('[pattern]').each(function() {
if (!$(this).val().match($(this).attr('pattern')))
alert('Bad value');
});
If not, you can do something for this (similar):
var inputs = getElementsByName('input');
for (var index in inputs) {
var input = inputs[index];
var pattern = input.getAttribute('pattern');
if (pattern != '' && pattern != null) {
if (!input.value.match(pattern))
alert('Bad value');
}
}
These will loop through the attributes that have a pattern to identify against, check them, and alert the user if there's a problem.
Of course, you can change the alert to whatever way you would like to handle it (for example, return false to cancel the form submission).
I haven't tested this code, but that's the gist of it.

You can use polyfill or add onchange event to your input.
document.getElementById('phone').addEventListener('change', function(){\
// returns true if input matches regexp, otherwise it returns false
var isValid = RegExp(this.pattern).test(this.value);
});

var regex = /^(?:\(\d{3}\)|\d{3})[- ]?\d{3}[- ]?\d{4}$/;
if(phone.value.match(regex)){
console.log('true');
}else{
console.log('false');
}
I just ended up using this... It worked. #_#

Related

How to Restrict to take input in JQuery from a input field Consisting on Alphabets without Space

I want to take an input from a text field and value should be consisting on alphabets and there should not be any space in between? Kindly let me know how to achieve this? Code is as follows;
$("#xxxx").bind("keyup change", function () {
$(this).val($(this).val().replace(/ /g,""));
});
Get to know regexes. They are fun, and you can test them here: https://regex101.com/
Use a regex in the replace that finds all non-alpha characters:
// no-conflict-safe document ready
jQuery(function($) {
// bind using on to a *class* instead of an id.
$(".numbers-only").on("keyup blur", function() {
// use a regex that finds all non-alpha characters
$(this).val($(this).val().replace(/[^a-z]/ig, ''));
});
});
Working fiddle: https://jsfiddle.net/cale_b/602wuwmx/
Notes for improving your code:
1. Use on instead of bind. (Per the bind documentation, bind was superseded by the .on() method for attaching event handlers to a document since jQuery 1.7, so its use was already discouraged.)
2. Bind to a class rather than an id. In this way, you can make multiple inputs behave this way.
You just check with regex if there is only alphabets:
var value = 'asdasd';
var isValid = value.match(/^[a-zA-Z]$/);
if (isValid) {
// valid
} else {
// not valid
}

JavaScript issue on checking if both numeric values exists

Hopefully I get this format right. I know this is a newbie question and probably pretty obvious but I am confused on how to check these fields. I have two input fields on a JSP file:
<input id="CMDScheduleNumber" type="number" class="textsmall" maxlength="5"
onKeyPress="return numbersonly(this, event)"/>
<input id="CMDContractYear" type="number" class="textsmall" maxlength="4"
onKeyPress="return numbersonly(this, event)"/>
I have a function in a script called "searchEFT" that is checking if either the schedule number or contract year is populated then both must be populated.
<script type="text/javascript">
//function for onchange
$(document).ready(function () {
$("#searchEFT").click(function () {
var Cmd_Sched_Number = document.getElementById("CMDScheduleNumber");
var Cmd_Contract_Year = document.getElementById("CMDContractYear");
var Cmd_Status = document.getElementById("CMDSchedStatus");
var Cmd_Creation_Date = ocument.getElementById("CMDCreationDate");
if (Cmd_Sched_Number == "") {
If(Cmd_Contract_Year !== "")
alert("Schedule Number and EFT Contract Year must be both populated");
return;
}
else if (Cmd_Sched_Number == "") {
alert("Schedule Number and EFT Contract year must be both populated");
return;
}
When I tried to do a debugger if the Cmd_Sched_Number field the value is shown as "" but the valueasnumber is shown as 'NaN'. So when I do a check, should I check it was "" or check it as numeric with isNaN and/or IsNull?
Thanks for the help
var Cmd_Sched_Number = document.getElementById("CMDScheduleNumber");
Gets the Element.
Use .value to get value from the Element
Something like:
var Cmd_Sched_Number = document.getElementById("CMDScheduleNumber").value;
Also, since you have jQuery already, consider using it.
Like:
var Cmd_Sched_Number = $("CMDScheduleNumber").val();
Custom code validations are really a mess. How many conditions you can check? There are a lot of open source libraries and they do the job pretty much well.
I would recommend you to use validate.js. Its very simple and easy to use. It sets the rules on the fields and validate according to them.
Probably you will have to do little more efforts right now to shift your code, but it will be very easy then.
As Aragorn correctly pointed out, make sure you're getting the values, not the Jquery objects or DOM elements.
function isPopulated(val) {
return !(val === '' || isNaN(val));
}
//and then in your click event handler...:
if((isPopulated(Cmd_Sched_Number) || isPopulated(Cmd_Contract_Year)) && !(isPopulated(Cmd_Sched_Number) && isPopulated(Cmd_Contract_Year))) {
//Handle the case where one is populated and the other isn't, assuming you want to treat any non-numbers as not populated.
}
This is if you want a common block for any scenario of one populated and the other not, it will be evaluated like an XOR.
The reason my isPopulated function checks for both an empty string and isNaN is that isNaN('') will evaluated false.
If you don't care whether the entered value is actually numeric or not, then you would maybe want to check value.length > 0, for example.

Using regex in javascript

I cannot get to work the following example of Regex in JavaScript. Regex is valid, was tested on some webs testing Regex expression.
I want it to check if input is in format: xxx,xxx,xxx.
It is alerting wrong input all the time. Thanks for any help.
var re = /[0-9a-zA-Z]+(,[0-9a-zA-Z]+)*/;
var toValidation = document.getElementsByName("txtSerial").value;
alert(toValidation);
if(!re.test(toValidation))
return true;
else
{
alert("Please insert valid text.");
return false;
}
document.getElementsByName("txtSerial") will return all elements by that name (node collection). Node collections do not have an attribute named value, thus, .value will be undefined (as can be seen by your alert).
Depending on your markup, you will want to use
document.getElementById("txtSerial")
or
document.getElementsByName("txtSerial")[0]
(although the last one is certainly not ideal).

How to avoid javascript retrieving values from non-existing elements

Update: clarified question (I hope)
Hi.
I'm developing a plugin in Wordpress and I'm outputting elements according to user privileges A and B.
In case of A, I ouput element "Foo".
In case of B, I output element "Bar".
Up till now, I haven't checked if an element exists before I try to retrieve the value.
This of course gives me a javascript error in some browsers (like IE7).
I've looked at using the typeof() function:
if(typeof(element) == 'undefined') {
//do something...
}
I'm also using jQuery. So one solution could be using this:
if ($("#mydiv").length > 0){
// do something here
}
Using the above methods, makes me having to check each element before trying to retrieve any values.
The "ideal" solution would be to get values based on user privileges. E.g:
if (userPriv == A) {
//get values from element 'Foo'
}
This way I can check once, and do the data gathering. The only solutions I can think of are setting the value of a hidden input element or use cookies.
<input type="hidden" id="userPriv" value="A" />
The other solution would be adding a value to the cookie.
setcookie("userPriv", "A");
Unfortunately, this last option gives me a warning message saying that cookie must be set in header (before html output). I think it's because I'm doing this in Wordpress.
I'm looking for opinions on which method is "the best way" to accomplis this.
Forgive me if I'm missing something, but checking for a DOM element in javascript is usually pretty easy.
var elementA = document.getElementById('id_of_a');
var elementB = document.getElementById('id_of_b');
if (elementA) {
//...
} else if (elementB) {
//...
}
The key is the if statement. getElementById will return nothing null if the element is not found, which will evaluate to false in the if statement.
Alternatively, if you don't really want to check for existence of individual DOM elements, can you send the users priv in a hidden input and act on that? That's a cookie free way of sending values clientside. Something like (edited to have jQuery code instead)
<input type="hidden" id="userPriv" value="A" />
...
var priv = $('#userPriv').val();
if (priv == 'A') {
//...
}
I'd still recommend checking for individual elements over checking a hidden input. It seems cleaner to me, more along the unobtrusive lines
You can use object as associative array:
var map = new Object();
map[A.toString()] = new Foo();
map[B.toString()] = new Bar();
In that case is much simpler to check and you will avoid "spaghetti code".

how to control the numbers of characters (numerics) with jquery

i need to control the numbers of characters in an input field using jquery ...
ive got some control already but, i dont know what else to do ....
var foo = function(){
if($('#foo1').val() == ''){
$('.foo_foo_c').load('../html/message_error_number.html');
}else{
$('.foo_foo_c').load('../html/foo_foo.html',function(){
listaStyle();
listaPagadasStyle();
listaDetalleLlamadasStyle();
});
}
};
Look at using the jQuery validation plugin and set up maxLength or rangeLength rule in addition to requiring that it be a number.
I think you want something like the Alphanumeric plugin.

Categories