i don't know much regex so if some one can help me with this it would be great i have a input box and a button.
if the user enters A12345678 the first character should always be A and the rest should always be numbers and altogether it should have less then 10 characters
<input type="textbox" id="id" />
<input type="submit" id="submit" />
<script type="text/javascript">
/*Check if ID is correct */
$('#id').keyup(function(){
var id= $(this).val();
if(id == /*'A12345678' */{
//enable button
}else{
// disable button
});
</script>
i would appreciate if some one could help me out a bit with this
Here ya go ^(A\d{1,9})$;
^ will start the verification at the beginning of the string
() encapsulates your result. not necessarily needed, but I like to have them
A will match the uppercase character
\d{1, 9} will match 1 to 9 numbers following the letter A
$means the end of the string
Use:
if(id.match(/^(A\d{1,9})$/)) {
// do stuff
}
Hope this helps.
Watch it work: https://jsfiddle.net/ppmr12v6/
Related
I have a problem, that I'm struggling with since 2 days.
I have a webpage that asks for the phone number, and I'm trying to make a "validator" for the phone number into the input tab, but it seems that I cannot figure out how to check the minlength for the input tab, neither how to accept only numerical characters. Here's the code:
$("#start").click(function(){ // click func
if ($.trim($('#phonenr').val()) == ''){
$("#error").show();
I tried adding:
if ($.trim($('#phonenr').val()) == '') && ($.trim($('#phonenr').val().length) < 15)
But it just won't work.
Any help would be appreciated. Also please tell me how can I make it allow only numbers?
Thank you!
Final code, with help of #Saumya Rastogi.
$("#start").click(function(){
var reg = /^\d+$/;
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$("#error").show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$("#error").show();
} else {
You can make your validation work.
You can use test (Regex Match Test) for accepting only digits in the input text. Just use javascript's substring to chop off the entered non-digit character like this:
$(function() {
$('#btn').on('click',function(e) {
var reg = /^\d+$/; // <------ regex for validatin the input should only be digits
var input_str = $('#phonenr').val();
chopped_str = input_str.substring(0, input_str.length - 1);
if(!reg.test(input_str)) {
$('label.error').show();
return;
}
if(($.trim(input_str) == '') || ($.trim(input_str).length < 15)) {
$('label.error').show();
} else {
$('label.error').hide();
}
});
})
label.error {
display: none;
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="phonenr" type="text" value=""><br>
<label class='error'>Invalid Number</label>
<br><br>
<button id="btn">Click to Validate</button>
Hope this helps!
If you are using HTML5, then you can make use of the new number input type available
<input type="number" name="phone" min="10" max="10">
You can also use the pattern attribute to restrict the input to a specific Regular expression.
If you are looking for the simplest way to check input against a pattern and display a message based on validity, then using regular expressions is what you want:
// Wait until the DOM has been fully parsed
window.addEventListener("DOMContentLoaded", function(){
// Get DOM references:
var theForm = document.querySelector("#frmTest");
var thePhone = document.querySelector("#txtPhone");
var btnSubmit = document.querySelector("#btnSubmit");
// Hook into desired events. Here, we'll validate as text is inputted
// into the text field, when the submit button is clicked and when the
// form is submitted
theForm.addEventListener("submit", validate);
btnSubmit.addEventListener("click", validate);
thePhone.addEventListener("input", validate);
// The simple validation function
function validate(evt){
var errorMessage = "Not a valid phone number!";
// Just check the input against a regular expression
// This one expects 10 digits in a row.
// If the pattern is matched the form is allowed to submit,
// if not, the error message appears and the form doesn't submit.
!thePhone.value.match(/\d{3}\d{3}\d{4}/) ?
thePhone.nextElementSibling.textContent = errorMessage : thePhone.nextElementSibling.textContent = "";
evt.preventDefault();
}
});
span {
background: #ff0;
}
<form id="frmTest" action="#" method="post">
<input id="txtPhone" name="txtPhone"><span></span>
<br>
<input type="submit" id="btnSubmit">
</form>
Or, you can take more control of the process and use the pattern HTML5 attribute with a regular expression to validate the entry. Length and digits are checked simultaneously.
Then you can implement your own custom error message via the HTML5 Validation API with the setCustomValidity() method.
<form id="frmTest" action="#" method="post">
<input type="tel" id="txtPhone" name="txtPhone" maxlength="20"
placeholder="555-555-5555" title="555-555-5555"
pattern="\d{3}-\d{3}-\d{4}" required>
<input type="submit" id="btnSubmit">
</form>
Stack Overflow's code snippet environment doesn't play well with forms, but a working Fiddle can be seen here.
UPDATE** Using the solutions provided below I added this with no luck?
<script>
$('.LogIn_submit').on('click',function(){
var value=$('#Log_In_group_2_FieldB').val();
value=value.replace(/^\s\d{6}(?=\-)&/, '')
alert(value);
});
</script>
Here are the form elements if, hoping it's a simple fix:
<input id="Log_In_group_2_FieldB" name="Log_In_group_2_FieldB" type="password" value="<?php echo((isset($_GET["invalid"])?ValidatedField("login","Log_In_group_2_FieldB"):"".((isset($_GET["failedLogin"]) || isset($_GET["invalid"]))?"":((isset($_COOKIE["RememberMePWD"]))?$_COOKIE["RememberMePWD"]:"")) ."")); ?>" class="formTextfield_Medium" tabindex="2" title="Please enter a value.">
<input class="formButton" name="LogIn_submit" type="submit" id="LogIn_submit" value="Log In" tabindex="5">
/***** Beginning Question ******/
Using this question/answers's fiddle I can see how they used javascript like this:
$('.btnfetchcont').on('click',function(){
var value=$('#txtCont').val();
value=value.replace(/^(0|\+\d\d) */, '')
alert(value);
});
I currently have a value that starts with 6 characters, ends in a dash and the up to 3 digits can follow the dash.
Exmaple 1: 123456-01
Example 2: 123456-9
Example 3: 123456-999
I've tried to insert a - in the value.replace cod with no luck. How do I remove the - and any values after this on submit so that I'm only submitting the first 6 digits?
Seems that you want to have only first 6 characters from the string.
Use .split() or substring(start, end) to get the parts of string.
var string = "123456-01";
console.log(string.split('-')[0]);
console.log(string.substring(0,6));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use split instead of regex
value=value.split("-")[0];
fix for your regex
/(-[0|\+\d\d]*)/g
function extractNumber(value){
return value.replace(/(-[0|\+\d\d]*)/g, '');
}
console.log(extractNumber("123456-01"));
console.log(extractNumber("123456-9"));
console.log(extractNumber("123456-999"));
Edit: the .split('-') answer is better than the following, imo.
Assuming you always want just the first 6 characters, something like this should do what you want:
$('.btnfetchcont').on('click',function(){
var value = $('#txtCont').val();
value = value.substr(0, 6);
alert(value);
});
or combine the two lines:
var value = $('#txtCont').val().substr(0, 6);
Read about .substr() here.
If you want to get everything before the dash, do something like this:
var value = $('#txtCont').val().match(/(\d*)-(\d*)/);
value is now an array where value[0] is the original string, value[1] is every digit before the dash, and value[2] is every digit after the dash.
This works for digits only. If you want any character instead of just digits, replace \d with .. i.e: .match(/(.*)-(.*)/).
Hi I have looked around online and I am aware that similar questions have been asked, however, I am unable to find a suitable solution to my problem. I need this code to be password validated, the problem is that I'm not directly working with an <input> field therefore I've been unable to figure out how to implement JS.
Here is the HTML (it's implemented using ruby-on-rails, this is all the 'HTML' side that I can see (full code in fiddle below))
<form accept-charset='utf-8' method='post' name="form" action='register' class="registerform" onsubmit="return validate_form()">
<h3 class="registernospace">Contact Information</h3>
<table>
<tbody>
<tr><td class="registerrowspace" colspan="2">The Password must be at least 6 characters long and should contain a mixture of lower case letters, upper case letters, and numbers.<br />The Confirm Password must match the Password.</td></tr>
<tr><th class="registerrowspace">Password</th><td id="password1" class="registerrowspace"><%= field('password') %></td></tr>
<tr><th class="registerrowspace">Confirm Password</th><td id="password2" class="registerrowspace"><%= field('password') %></td></tr>
<tr><th class="registerrowspace">Date of Birth</th><td class="registerrowspace">
</tbody>
</table>
<% end %>
<input type='hidden' name='register_submitted' value='yes'/>
<p><input type='submit' class="button" value='Register Now' /></p>
</form>
And I have tried Implementing some JS (but being unfamiliar with the language I haven't been able to get it working, but I was trying to do something like this:
<script type="text/javascript">
function validate_form()
{
var passw = document.getElementById('password1').value;
if(passw.value.length < 6 ) {
alert("Error: Password must contain at least six characters!");
form.password.focus();
return false;
}
return true;
}
</script>
So I was hoping it validates and raises a message if its blank, if its < 6 chars and if it does not include a Uppercase and a number. Although I'm aware I haven't introduced the latter in the code, I couldn't even get the <6 to work.
Also I have other validations (which were built by default which work) and you can see the full:
Fiddle code
Live Website
if(passw.value.length < 6 ) {
should be
if(passw.length < 6 ) {
because you already get its value
var passw = document.getElementById('password1').value;
UPDATE:
password1 is <td> id not of password feild
i just check your link, it was giving error passw is undefined in console, you password field id is password-input-0, so use
var passw = document.getElementById('password-input-0').value;
^.*(?=.{6,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$
---
^.* : Start
(?=.{6,}) : Length
(?=.*[a-zA-Z]) : Letters
(?=.*\d) : Digits
(?=.*[!#$%&? "]) : Special characters
.*$ : End
function validatePassword() {
var newPassword = document.getElementById('changePasswordForm').newPassword.value;
var regularExpression = ^.*(?=.{6,})(?=.*[a-zA-Z])(?=.*\d)(?=.*[!#$%&? "]).*$/;
alert(newPassword);
if(!regularExpression.test(newPassword)) {
alert("password should contain atleast one number and one special character");
return false;
}
}
Instead of using if(passw.value.length < 6 ) use if(passw.length < 6 ) you have already value of password you only need to check for size.
Also, Your textfield name is wrong. 'Password1' is td name not password textfield. Please check and correct.
if(passw.length < 5 ) //here should be 5
Page refreshes when you click the button :you don't call e.preventDefault(); I think you should listen 'submit' event. In the 'listen' function you may validate the length of the input and prevent it's default behavior.
I have a form with three elements. I want to validate the phone number when the user enters it. If the user moves to the next element and phone number contains and characters which is not numbers I want to display an alertbox.
I have written some code but am completely stumped. The problem I am having with my function is, that even if I enter only numbers into the phone number element I still get the alert box displayed. My code looks like this:
<script type="text/javascript">
function validateForm()
{
checkNr= isNaN(document.forms[0].elements[1])
if(checkNr == true)
{
window.alert("You can only enter numbers. Please try again")
}
}
</script>
<form>
<strong>FULLNAME: </strong><input type="text" / id="name"><br />
<strong>PHONE NR: </strong><input type="text" id="phone" onblur="validateForm()" />
<strong>NATIONALITY</strong><input type="text" id="nat" /><br />
<input type="button" id="subButton" onclick="calc()" value="Submit" />
</form>
Thank you in advance for all your answers and help.
Change
document.forms[0].elements[1]
to
document.forms[0].elements[1].value
You were testing the element itself, not the element's value.
jsFiddle example
BTW, if someone enters a phone number with a dash or parenthesis (e.g. (555) 123-4567) what do you expect to happen?
Here you will find many exemple to achieve your goal :
for example if you can use only number :
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}
You should do it with a regular expression. See here:
A comprehensive regex for phone number validation
Validate phone number with JavaScript
I'm a novice when it comes to Javascript.
I would like to improve the search in the script provided below.
I have the following code and currently when I type the phrase 'blue widgets' in search, it will only identify/find the checkbox if the phrase 'blue widgets' exits in sequence. For example, If I have a keyword phrase or sentence that contains 'blue cool widgets' and I search for 'blue widgets' it is unable to locate that even though blue and widgets both exist in my keyword phrase.
Could it be possible that if I search for a phrase with 2 or even 3 words in it, then it can find any keyword phrase/sentence on my page in which all words of my search phrase exist and then check the box (which the code already does). The only condition is that all the words of my search phrase have to exist in a sentence/string ?
I would very much appreciate if this solution can be found.
<html>
<head>
<script type="text/javascript">
function checkForWord( wordField )
{
var form = wordField.form;
var word = wordField.value.replace(/^\s+/,"").replace(/\s+$/,"").toLowerCase();
var inputs = form.getElementsByTagName("input");
for ( var e = 0; e < inputs.length; ++e )
{
var field = inputs[e];
if ( field.type == "checkbox" )
{
if ( field.value.toLowerCase().indexOf(word) >= 0 )
{
field.checked = true;
} else {
// OPTIONAL, if you do NOTwant to clear previously checked boxes, omit next line:
field.checked = false;
}
}
}
}
</script>
</head>
<body>
<form onsubmit="return false;">
Type a word: <input name="word" onchange="checkForWord(this);" />
<hr>
<label>
<input type="checkbox" name="keywords" value="This is an example sentence with blue and cool widgets not in order and my current script will not find it.
</label></br/>
<label>
<input type="checkbox" name="keywords" value="This sentence will be found if I search for blue widgets because its in this sentence">
All work and no play makes Jack
</label></br/>
<label>
<input type="checkbox" name="keywords" value="I would like for it to be able to find this sentence also since blue and widgets both words exist but are out of order.
</label></br/>
</form>
</body>
</html>
It would be the best to tokenize your search string (split it by words), execute each search independently (for every word) and then merge results.
/(?=.*blue)(?=.*widgets)/.test( phrase );
(?=...) is a look-ahead, meaning it only matches if the expression is matched somewhere further in the string. The nice part is that it doesn't consume the match, so the above will only match if you have "blue" and "widgets" at some point later in the string, but order doesn't matter.
Feel free to modify those to wrap with whitespace if necessary so that it only matches the entire word (e.g. wrap the words with \b)
To generate that regex dynamically:
var words = 'blue widgets';
new RegExp( '(?=.*' + words.split( /\W+/g ).join( ')(?=.*' ) + ')', 'i' )