In the code below, I have a phone number field and what I want to achieve is make sure each number is 15 digits and also ensure that if multiple phone numbers are entered (comma separated) (see code to understand), they too are 15 digits.
$("#btn").on('click',function(){
var regrExpr = new RegExp("^(?=\S{10,}$)(?=.*\d{15},?).*");
//var regrExpr = new RegExp("\d{15}(?:,\d{15})*");
//var regrExpr = new RegExp("\d{10,15}(?:,\d{10,15})*");
//var regrExpr = new RegExp("^(\d{15}[,]{0,1})+$");
//var regrExpr = new RegExp("^\+\d{10,15}(,\+\d{10,15})*$");
//var regrExpr = new RegExp("^(?=\S{10,}$)(?=.*\d{15},?).*");
if (!regrExpr.test($("#txt").val()))
{
alert("Please Enter No");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" id="txt" style="width:300px">
<button id = "btn">Check</button>
Regex'ically, I need something like this :
~^[0-15]{15}(?:,[0-15]{15})*$~
Found this here
But, it doesn't work in my case.
here is the working regular expression of your case.
^\+\d{10,15}(,\+\d{10,15})*$
I believe the best regex would be
^(?=\S{10,}$)(?=.*\d{15},?).*
check the demo at here
here
(?=\S{10,}$)
ensures that the string is atleast of length 10
(?=.*\d{15},?)
is responsible for matching if number is of 15 length and is comma seperated
Use /.../ notation to define regex:
$("#btn").on('click',function(){
var regrExpr = /^\d{15}(?:,\d{15})*^/;
if (!regrExpr.test($("#txt").val())) {
console.log("Invalid number, retry");
return false;
} else {
console.log("All correct")
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="tel" id="txt" style="width:300px">
<button id = "btn">Check</button>
Finally i got a solution
Check this Answer
var pattern = /^(?:\s*\d{15}\s*(?:,|$))+$/;
if(pattern.test($("#txt").val())){
alert("Correct");
} else {
alert("Wrong");
}
``
Related
Hi I am not a javascript expert thats why I will really appreciate any advice
I have a textfield named try where in I will input something
ex:
try value is
87
then I have another textfield named field11
field11 has a value of
777-a98;87-bx23;000-t88;245-k7
I wanted to compare try and field11 if try is found in the content of field 11 it will set the textfield named msg to 87-bx23 matched
msg value will be
87-bx23 matched
my code is like this but its not giving the desired output I know my comparison is wrong it just I dont know how
<script>
$(document).ready( function(){
$('#submit').click(function() {
if (document.getElementById('try').value != document.getElementById('field11').value)
{
alert('dont match!');
$("#msg").val ("dont match!");
}
else if (document.getElementById('try').value == document.getElementById('field11').value) {
}alert(document.getElementById('try').value + " exists");
$("#msg").val(document.getElementById('try').value + " exists");
});
});
</script>
I also try this but if I input 77 it saying it exist even not
<div id="requirement #2">
<button type="button" id="button2" onclick="StringSearch()">Search</button>
</div>
<script>
function StringSearch() {
var SearchTerm = document.getElementById('try').value;
var TextSearch = document.getElementById('field11').value;
if (SearchTerm.length > 0 && TextSearch.indexOf(SearchTerm) > -1) {
alert("Patient Exists");
} else {
alert("Patient Does not exist click add if you want to add the patient");
$("#msg").val(document.getElementById('try').value + " exists");
$("#t1").val("1");
}
}
</script>
document.getElementById('field11').value.match(new RegExp("(" + "87" + "-[a-z0-9]+);"))[1])
The Generated Regex when try value = 87:
/(87-[a-z0-9]+);/
So what is this monstrosity? We generate a Regex Expression, that looks for the try value followed by a dash, and one or more characters from a-z or 1-9, followed by a semicolon. String.match() is used to determine an array of matches, the array[1] is the first capture group (the part of the RegEx between the brackets), which is in this case 87-bx23
I have tried to rewrite your code to store variables for the elements and use a Regexp to do the search for the value:
<script>
$(document).ready( function(){
var tryElem = document.getElementById('try');
var field1 = document.getElementById('field11');
$('#submit').click(function() {
var regex = new Regexp(tryelem +'[^;]*');
var match = regex.exec(field.value);
if (match)
{
alert(match + " exists");
$("#mag").val(match + " exists");
}
else
{
alert('dont match!');
$("#msg").val ("dont match!");
}
});
});
</script>
The code does more or less the same as yours, except for the regex:
tryelem +'[^;]*'
It builds a regular expression form the the value of tryElem and then it searches forward and matches up to the first semi colon (zero or more characters).
Now the match will contain: '87-bx23'.
You can try this:
<input type="text" id="try"/>
<input type="text" id="field11" value="777-a98;87-bx23;000-t88;245-k7"/>
<input type="text" id="msg"/>
<input type="button" id="submit"/>
And js:
$(function(){
$("#submit").click(function(){
var Try=$("#try").val(),
f11=$("#field11").val(),
msg=$("#msg");
//but if you want search in number part only (before dash sign), uncomment line below and comment next line.
//var r=((";"+f11+";").match(new RegExp(";([^;-]*"+Try+".*?-.+?);"))||[])[1];
var r=((";"+f11+";").match(new RegExp(";([^;]*"+Try+"[^;]*);"))||[])[1];
msg.val(r||"don't match!!");
});
});
You can check or change both of them online
what I want is If the enter text box value is in format or not (1-10 number hyphen number) i did this for one pattern matching /^[\d]+([-][\d]+)?$/g but it allows only 0-9(single digits) i not taking 11-20(double digits) I need to allow any type digits like 10-11 and how can i do this
var txt = document.getElementById("txtShareCount").value;
if(txt.match(/^[\d]+([-][\d]+)?$/g)){
return true;
}
else if(!txt.match( /^[\d]+([-][\d]+)?$/g)){
alert("Pleae Enter Share count this(1-10) format");
document.getElementById("txtShareCount").focus();
return false;
}
else{return true;}
Here i'm posting the OP post as executable snippet to show his code is working perfect . i said in comment he didn't accept that . so only i'm posting this snippet .
1) Additionally i applied only trim()
$('#ss').click(function(){
var txt = $("#txtShareCount").val();
if(txt.trim().match(/^[\d]+([-][\d]+)?$/g)){
alert("hi valid format ");
}
else if(!txt.trim().match(/^[\d]+([-][\d]+)?$/g)){
alert("Pleae Enter Share count this(1-10) format");
$("#txtShareCount").focus();
return false;
}
else{
alert("hi valid format ");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inputt"><input type="text" id="txtShareCount" name="myanswer" class="myinput"></div>
<input type="button" id="ss" value="submit" >
The regex ^[\d]+([-][\d]+)?$ accomplishes what you need
function EnterCandidates() {
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
names = document.querySelectorAll('label[for^=V][id^=L_V]');
Array.prototype.forEach.call(names, function(label, index) {
if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
label.textContent = candidateNameInputs[index].value;
}
});
}
I have this code which gets the users input and changes the label with it but i want to add some code which only allows the user to enter letters of the alphabet. How would I go about this using this code?
If you are using modern browsers then user html5 validation -
<input type="text" name="name" class="field" pattern="[a-zA-Z ]+" />
It accepts a-z and A-Z plus space
listen to keyDown event and match with this regex:
/[a-zA-Z]+/
if you're targeting modern browsers only, you can try this:
<input type="text" pattern="[a-zA-Z]" title="Only letters" />
you can't avoid that the user types non alphabetic characters. But you can:
- control the input fields (onkeydown) and check if there are some characters you don't want Stackoverflow - force input to only alpha-letters
- do the same before the
label.textContent = candidateNameInputs[index].value;
line and filter/replace the characters you don't want
var val = document.getElementById('id').value;
if (!val.match(/^[a-zA-Z]+$/))
{
alert('Only alphabets are allowed');
return false;
}
full script
function EnterCandidates() {
console.log('woo');
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
names = document.querySelectorAll('label[for^=V][id^=L_V]');
Array.prototype.forEach.call(names, function (label, index) {
if (!candidateNameInputs[index].value.match(/^[a-zA-Z]+$/))
{
alert('Only alphabets are allowed');
}
else
{
if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
label.textContent = candidateNameInputs[index].value;
}
}
});
}
Here is one way to do it using Javascript.
http://jsfiddle.net/q60gm0ra/
var input = document.getElementById('alpha');
input.addEventListener('keypress',function(e) {
var str = String.fromCharCode(e.charCode);
if (!(/[A-Z]|\s/i).test(str)) {
e.preventDefault();
}
});
Hi have a form with a few fields. Amongst them:
<div>
<label for="phoneNumber" class="label">Phone Number</label>
<input name="phoneNumber" type="text" id="phoneNumber" size="13" style="float:left;margin-right:10px;">
</div>
<div>
<input type="checkbox" name="activePN" id="activePN" checked >
<label for="activePN">Active</label>
</div>
The, when the form is submited, I want to validate the input and write next to each field for whichever field didn't validate. Like this:
$('#submit').click(function () {
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, '').toString(); //strips non-digits from the string
if (strippedPN.length !== 10) {
$('#phoneNumber').text('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
...
...
...
});
I was hopping that adding those <p> </p> tags would do it. But they don't...
Note: I also tried with html() instead of text() and with activePN instead of phoneNumber.
Use .after().
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
It might be wise to add a class to your p tag too, so you can remove them when the number is edited to be correct.
Try:
$('#submit').click(function(){
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, ''); //strips non-digits from the string - already a String
if(strippedPN.length !== 10){
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
}
Its best to use jqueryvalidation plugin.
But in some scenario may be you need to show validation message using custom code, then below may help.
Code
var errorSeen = false;
$('#txtname').keyup(function (e) {
var validInput = false; // TODO set your validation here
if (!validInput) {
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorSeen === false && errorMessageVisible === false) {
$('#txtname').style.borderColor = "red";
$('#txtname').after("<span class='validationMessage' style='color:red;'>
Name is required.</span>");
errorSeen = true;
}
}
else {
$('#txtname').style.borderColor = "";
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorMessageVisible)
$(".validationMessage").remove();
errorSeen = false;
}
});
I want to check the gap between two or more words, i have given as an input, in a text box. If there had any space, then i want to alert user that no space is allowing. I can check the existence of text simply using "if else" statement. But can't do the desired stuff in this way. My code is given below :
<script type="text/javascript">
function checkForm()
{
var cName=document.getElementById("cName").value;
var cEmail=document.getElementById("cEmail").value;
if(cName.length<1)
{
alert("Please enter both informations");
return false;
}
if(cEmail.length<1)
{
alert("Please enter your email");
return false;
}
else
{
return true;
}
}
Name : <input type="text" id="cName" name="cName"/>
<br/>
<br/>
Email : <input type="text" id="cEmail" name="cEmail"/>
<br/>
<br/>
<input type="submit" value="Go!"/>
</form>
Thankyou
Just use the match() method of strings. For example:
'Spaces here'.match(' ');
That returns true.
'Nospace'.match(' ');
That returns false.
So for what you want, just use something like this:
if(cName.match(' ')){
alert('Spaces found!');
return false;
}
Demo
your question not very clear , but i hope you want to count your words you can use the following code to split a text and by using the length property you count the word
var b = document.getElementById("cName").value;
var temp = new Array();
temp = b.split(' ');
var count= temp.length;
and if you want to validate your name field that should not use any space
if ( ^[A-Za-z]$.test(document.getElementById("cName").value) ) {
// your code;
}
if ( document.getElementById("cName").value.indexOf(' ') > 0 ) {
alert('space found');
}