I have a textbox whereby the user needs to input his/her mobile number. However I need to validate the first 2 numbers (characters) to make sure that the mobile number is in the correct format (as one of the validation rules).
The mobile number needs to start with any of the following 2 digits:
44xxxxxx
55xxxxxx
65xxxxxx
78xxxxxx
Can anyone tell me how it's possible to validate the first two characters number and check that they are either one of the options mentioned above?
EDIT
This is what I had tried but it did not work:
HTML
<input id="mob" name="mob" type="tel" placeholder="Enter your mobile number">
Validate
JS
var mobile_prefix = $('#mob').subsubstr(0,2);
$('#validate').click(function(){
if (mobile_prefix == 44||55||65||78) {
alert('correct');
}
else {
alert('incorrect');
}
});
I think .match() has what you're looking for. Just brush up on some regular expressions.
if (StringFromSelectField.match(/^(44|55|65|78)/)) {
//do something
}
Use substring from javascript
var FirstTwoLetters = TextFromYourInput.substring(0,2);
and then you can compare first two letters with your pattern.
Using a regular expression would probably be the easiest:
({phone number}).match(/^(44|55|65|78).*$/)
So first variable for input filed;Kind of my way;)
first check if that input is not empty and has 3 or more signs.
On the end is variable which I use on the end to allow form.submit().
If you want you can add before each getting val() $.trim(postcode.val()) != ''
var postcode = $('#post_code');
if(postcode.val() != '' && postcode.val().length > 2){
var shortPostCode = postcode.val().substring(0,2);
var validPostCode = /^(EH|KY)/;
if(!shortPostCode.match(validPostCode)){
postcode.after('<span class="error">Post code must start with EH</span>');
dataValid = false;
}
}
Related
I have one requirement in form.My form has textbox field "DEA License number".textbox must allow user to enter alphabet only for first two characters and numbers only after two characters.I want to achieve this functionality using javascript.Note:-I dont want validation but avoid user inputting
Have you tried using regex?
Take a look at this post which has a very similar goal: RegEx pattern any two letters followed by six numbers
Try use some of masked textbox.
For example:
https://css-tricks.com/input-masking/
http://digitalbush.com/projects/masked-input-plugin/
You can easily test this with a regex:
function isValid(str) {
return /^[a-zA-Z]{2}\d+$/.test(str);
}
I am not quite sure what you mean by "I dont want validation but avoid user inputting." If you mean that you don't want the user to be able to type an invalid character, this could theoretically be done with an input event handler:
var oldValue = "";
document.getElementById("test").addEventListener("input", function(e) {
var value = e.target.value;
if ((value.length <= 2 && /^[a-zA-Z]*$/.test(value)) || value.length > 2 && /^[a-zA-Z]{2}\d+$/.test(value)) oldValue = value
else e.target.value = oldValue;
})
However, you'd still need to validate it when it's submitted since the user could've entered an incomplete value.
How to check if a textbox contains numbers only?
While googling I came across this. But I'm wondering if isNumeric can be used for this purpose or if there are more simpler ways of checking if a textbox has a numeric value.
var query = $('#myText').val();
if (parseFloat(query) == NaN) {
alert("query is a string");
} else {
alert("query is numeric");
}
You can check if the user has entered only numbers using change event on input and regex.
$(document).ready(function() {
$('#myText').on('change', function() {
if (/^\d+$/.test($(this).val())) {
// Contain numbers only
} else {
// Contain other characters also
}
})
});
REGEX:
/: Delimiters of regex
^: Starts with
\d: Any digit
+: One or more of the preceding characters
$: End
Regex Visualization:
Demo
If you want to allow only numbers, you can use input-number and pattern
<input type="number" pattern="\d+" />
using pure JS regular expression
var query = document.getElementById('myText').value;
var isNumeric=query.match(/^\d+$/);
if(isNumeric){/*...*/}else{/*...*/}
or using html5 control
<input type="number" name="quantity" min="1" max="5">
There're many ways, you can use isNaN
isNaN(VALUE);
You can also use regEx to verify numeric values.
console.log(/^\d+$/.test(VALUE));
Jquery provides generic util method to handle this.
handles numeric/float/hex
$.isNumeric( value )
Try: fiddle
You can match the value of text box against the numeric regression to check if it contains numbers only or not, Like below code...
if($('#myText').val().match(/^\d+$/)){
// Your code here
}
Trying to figure out how to detect if two words have been typed in an inputbox with jquery or javascript.
I am not sure how to do this, I can do a character limit but cant quite figure out if two words have been typed.
This is just a question, I do not have any code to display as I do not know where to begin
Why not counting spaces ?
function howManyWordsInInput(id)
{
var text = document.getElementById(id).value;
text = text.split(" ");
return text.length;
}
Usage for 2 words : if (howManyWordsInInput("YourInputID") == 2) {...}
EDIT
For those who prefer single lined way :
if (document.getElementById("YourInputID").value.split(" ").length == 2) {...}
if$('input').val().split(/\s/).length===2){
// 2 words have been typed
}
And bind this to the keyup event.
There are other ways too. Many
note that this dosent account for the user typing non word characters or numbers.
Just use split to see how many words You have: http://fiddle.jshell.net/m4y9tscx/
How should I validate my textbox so that I the text entered shouldnt start with zero. I can enter zero anywhere else in the textbox...
function checkFirst() {
var text = document.getElementById('<%=textbox.ClientID %>').value.charAt(0);
if (text == "0") {
return false;
}
}
I tried with this code but it shows JavaScript Runtime error is thrown. I dont know how to clear it.
If there are any choices in regular expressions too pls suggest me some.
Use JQuery and JavaScript match function to check textbox value by using regular expression:
function checkFirst() {
var text = $('#<%=textbox.ClientID %>');
return text.val().match("^[1-9][0-9]*$") != null; //wil work only if you allow only numbers in your input, otherwise replace the regex.
}
You'll have to do the same check on server although. There you use asp:RegularExpressionValidator with same validation expression as on client side.
Use this regular expression to validate the textbox value -
^[a-zA-Z1-9][a-zA-Z0-9.,$;]+$
This will not allow 0 as the first character.
I am having a hard time figuring out how RegExp work.
I need to rewrite some ASP code into html and js, and I've hit an obstacle in this part:
<asp:RegularExpressionValidator runat="server" id="RegExpValidator" controltovalidate="FileName" Display="Dynamic" ValidationExpression="[^#%&*:<>?/{|}]+">
Now, what I do is create an input textbox which will run a js function whenever its content is changing.
<input type="text" id="fileNameTextBox" class="ms-input" size="35" maxlength="123" onchange="regexValidator(this);"/>
function regexValidator(control) {
var val = $(control).val();
if(val == undefined || val == '') {
$(control).attr("class", "invalid");
}
else {
// Regex stuff goes in here
}
}
Now, for the life of me I can't figure out how to construct the regular expression. The ValidationExpression field i assume checks for invalid characters though it doesn't seem to be a properly constructed regex, and I can't figure out how to write it into a proper one to use with js. Could someone help me out with this?
If you want the regex to check for invalid characters in the field, you can use this.
^.*?(?=[\^#%&$\*:<>\?/\{\|\}]).*$ This will give you a match if there is at least one invalid character.
You are almost there. Now you just need to make sure, that your string only consists of valid characters. Do this by adding anchors for the beginning and end of string, thus ensuring that the repeated sequence covers the whole string:
ValidationExpression="^[^#%&*:<>?/{|}]+$"
EDIT: I just realised that you probably also want to know how to create a regular expression from a string. You can simply pass a string to a regex constructor:
new RegExp(validationExpressionGoesHere);
[^#%&*:<>?/{|}]+ looks like a valid expression to me (although typically regular expressions are enclosed in forward-slashes). It's basically checking to see of the filename contains any of the illegal characters within the square brackets (apart from the caret ^ which indicates negation).
function regexValidator(control) {
var val = $(control).val();
if(val == undefined || val == '') {
$(control).attr("class", "invalid");
}
else if(val.match(/[^#%&*:<>?/{|}]+/)) {
// Valid
}
else {
// Invalid
}
}