Only allow HTML field to start with certain words - javascript

Is there a quick javascript library or code that would only allow a user to start a form input with a preset selection of words?
For example it would allow a user to start a the word "Are" or "What" but not "Why".

You can use the following Regex. (This is really primitive and should be improved according to your case.)
^(Why|Are).*$
HTML5 input pattern example:
<form>
<input type="text" pattern="^(Why|Are).*$">
<input type="submit">
</form>
Test here.

You can add change or input event listener to it and validate the content. To avoid false negatives with initial few letters you can start checking after the input string contains a space. You don't need a library to do that. Plain old JS will do the job.
var input = document.getElementById("myinput");
input.addEventListener('input', validate);
function validate(e) {
var validStart = ['why', 'when'];
var tmpVal;
if (this.value.indexOf(' ') !== -1) {
tmpVal = this.value.toLowerCase().trim();
if (validStart.indexOf(tmpVal) === -1) {
input.classList.add('notvalid');
} else {
input.classList.remove('notvalid');
}
} else {
input.classList.remove('notvalid');
}
}
JSFiddle: http://jsfiddle.net/ofx2yhzm/1/

Very similar to Strah's answer, but here it is anyway:
function checkValue(el) {
// Trim only leading whitespace so responds when first space entered
// and break into words
var words = el.value.replace(/^\s+/,'').split(/\s+/);
// List of allowed words
var allowed = ['are','what'];
// Element to write message based on source element
var msg = document.getElementById(el.id + 'Msg');
// Clear error message by default
msg.innerHTML = '';
// Only do something if at least one word has been entered
// Could also check if first word has more letters than
// longest allowed word
if (words.length > 1) {
// Check if first word is allowed
if ( allowed.indexOf(words[0].toLowerCase()) == -1) {
msg.innerHTML = 'Input must start with one of ' + allowed.join(', ');
}
}
}
Some markup:
<input id="foo" oninput="checkValue(this);">
<span id="fooMsg"></span>
This allows the user to at least enter a word before being given an error. They should also be given some onscreen hints to let them know which words to use, rather than having to get it wrong first (which is bound to happen a lot).

Html:
<form name="myform" method="post" action="#" onsubmit="return validate()">
<input type="text" name="val" />
<input type="submit" value="Submit" />
</form>
Javascript:
window.validate = function(){
data = document.forms['myform']['val'].value;
var starts = ['hi','he'];
for (var i = 0; i <= starts.length; i++)
if (data.indexOf(starts[i]) === 0) return true;
return false;
}
And of course you could also use Regex tho I guess that's a little more inefficient.
Something like this?: http://jsfiddle.net/4jasrbob/

Related

jQuery Click Function, input value length and pattern

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.

JavaScript string is not a function

When working on a page whenever I call on my second function, validateNumber(), I get a "typeError: String is not a function" message can anyone explain to me why this message is occuring? My code is as follows:
< script type = "text/javascript" >
/* <![CDATA[ */
function validateLetter(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = textInput.replace(/[^A-Za-z]/g);
if (textInput != replacedInput)
throw "You can only enter letters into this field.";
dataEntry.value = replacedInput;
} catch (textInputError) {
window.alert(textInputError)
return false;
}
return true;
}
function validateNumber(dataEntry) {
try {
var textInput = dataEntry.value;
var replacedInput = textInput(/[^0-9]/g);
if (textInput != replacedInput)
throw "You can only enter numbers into this field.";
} catch (numberInputError) {
window.alert(numberInputError)
return false;
}
return true;
}
function validateInput(dataEntry) {
if (navigator.appName == "Microsoft INternet Explorer")
var enteredKey = dataEntry.keyCode;
else if (navigator.appName == "Netscape")
var eneteredKey = dataEntry.charCode;
}
/* ]] */
< /script>
<form action="validateTheCharacters" enctype="application/x-www-form-urlencoded" name="dataEntry">
<p>Enter your mother's maiden name:
<input type="text" id="letter1" name="letter1" onkeypress="validateLetter(this)">
</p>
<p>Enter the city you were born in:
<input type="text" id="letter2" name="letter2" onkeypress="validateLetter(this)">
</p>
<p>Enter the street you grew up on:
<input type="text" id="letter3" name="letter3" onkeypress="validateLetter(this)">
</p>
<p>Enter your phone number:
<input type="text" id="number1" name="number1" onkeypress="validateNumber(this)">
</p>
<p>Enter the year you were born:
<input type="text" id="number2" name="number2" onkeypress="validateNumber(this)">
</p>
<p>Enter the number of siblings you have:
<input type="text" id="number3" name="number3" onkeypress="validateNumber(this)">
</p>
<p>
<button type="reset" value="Reset Form">Reset Form</button>
</p>
</form>
I am almost certain this is the problem:
var textInput = dataEntry.value;
var replacedInput = textInput(/[^0-9]/g);
if textInput is a string you cannot pass parameters to it as if it were a function, instead:
var replacedInput = textInput.replace(/[^0-9]/g, ""); // dependening in what you are trying to achieve of course
var replacedInput = textInput(/[^0-9]/g);
That's not how you do search and replace in Javascript.
It's not quite clear what you intended here, but if you wanted to remove non-digits from the string, you'd do that using String.replace():
var replacedInput = textInput.replace(/[^0-9]/g, "");
That being said, an easier way of accomplishing this check would be to skip the replacement entirely and just use String.match() instead:
var textInput = dataEntry.value;
if (textInput.match(/[^0-9]/))
throw "You can only enter letters into this field.";
dataEntry.value = textInput;
You might consider isolating functionality so that functions like validateLetter simply validate that the string they are passed contains only letters, then have the caller function work out what to do if the return value is true or not.
In that case, you end up with very much simpler functions:
function validateLetters(s) {
return /^[a-z]+$/i.test(s);
}
function validateNumbers(s) {
return /^\d+$/.test(s);
}
To validate an input, you can add a class to say what type of validation it should have, e.g.
<input name="letter3" class="letter" onkeypress="validateLetter(this)">
Then the validateInput function can determine which validation function to call based on the class:
function validateInput(element) {
var value = element.value;
// If has class letter, validate is only letters
if (/(\s|^)letter(\s|$)/i.test(element.className)) {
// validate only if there is a value other than empty string
if (!validateLetters(value) && value != '') {
alert('Please enter only letters');
}
}
// If has class number, validate is only numbers
if (/(\s|^)number(\s|$)/i.test(element.className)) {
// validate only if there is a value other than empty string
if (!validateNumbers(element.value) && value != '') {
alert('Please enter only numbers');
}
}
}
Note that keypress is not a good event to use for validation as data can be entered without pressing any keys (e.g. paste from the context menu or drag and drop). Also, the listener doesn't see the value resulting from the keypress, it sees the previous value.
You really only need to perform validation when the form is submitted. Until then, why do you care what the values are? Allow the user to make mistakes and fix them themselves without being pestered by alerts (onscreen hints are really useful). Spend some time using your forms to enhance their usability (I realise this is probably not a production form, but names can have characters other than the letters a to z, e.g. von Braun and O'Reilly).
Lastly, form controls rarely need an ID, the name is usually sufficient to identify them if required (and they must have a name to be successful, so most have a name already). A bit of play HTML from the OP:
<form>
<p>Enter your mother's maiden name:
<input name="letter1" class="letter" onkeypress="validateInput(this)">
</p>
<p>Enter the number of siblings you have:
<input name="number3" class="number" onkeypress="validateInput(this)">
</p>
<p>
<input type="reset">
</p>
</form>

Regular expression on textarea

I'm having a bit of trouble validating a form I have, I can check for only letters, numbers and a full stop ("period") in a single text input, but I can't for the life of me get it to work at all on a textarea field.
in my validation I have this:
var usernamecheck = /^[A-Za-z0-9.]{5,1000}$/;
the validation I've tried that doesn't work on the textarea ($ITSWUsers) is:
if(!document.all.ITSWUsers.value.match(usernamecheck))
{
alert ("Please write the usernames in the correct format (with a full stop between first and last name).");
return false;
}
however, the following on a 'input type="text"' works just fine on the same form
if(!document.all.SFUsersName1.value.match(usernamecheck))
{
alert("Usernames can only contain letters, numbers and full stops (no spaces).");
return false;
}
I need it to validate usernames, 1 name per line
e.g.
John.smith
Peter.jones1
these are both OK but the following wouldn't be:
John Smith
David.O'Leary
3rd.username
any help/pointers with this would be greatly appreciated
(I only know basic html/php/javascript)
To validate line by line, I'd use the split function to turn each line into an array. Then, loop through the array and run your RegEx on each line. That way, you can report exactly what line is invalid. Something like this:
<textarea id="ITSWUsers"></textarea>
<button onclick="Validate()">Validate</button>
<script>
var usernamecheck = /^[A-Za-z0-9]{5,1000}\.[A-Za-z0-9]{5,1000}$/;
function Validate()
{
var val = document.getElementById('ITSWUsers').value;
var lines = val.split('\n');
for(var i = 0; i < lines.length; i++)
{
if(!lines[i].match(usernamecheck))
{
alert ('Invalid input: ' + lines[i] + '. Please write the usernames in the correct format (with a full stop between first and last name).');
return false;
}
}
window.alert('Everything looks good!');
}
</script>
I'd trim the input from the textarea using JQuery (or a JS function), and then use this regex:
/^([A-Za-z0-9]+\.[A-Za-z0-9]+(\r)?(\n)?)+$/
Like so:
function testFunc()
{
var usernamecheck = /^([A-Za-z0-9]+\.[A-Za-z0-9]+(\r)?(\n)?)+$/;
if(!$.trim(document.all.ITSWUsers.value).match(usernamecheck))
{
alert ("Please write the usernames in the correct format (with a full stop between first and last name).");
return false;
}
}
<textarea id="ITSWUsers" cols="50" rows="10">
John.smith
Peter.jones1
</textarea>
<button onclick="testFunc()">Click Me</button>
See it working here:
http://jsfiddle.net/DkLPB/

Enable submit when all form items are valid

I need some help with something... say I have the following form...
<form name="" id="" method="" action="">
<input type="text" id="text1" name="text1" />
<br />
<br />
<input type="text" id="text2" name="text2" />
<br />
<br />
<input type="text" id="text3" name="text3" />
<br />
<br />
<input type="text" id="text4" name="text4" />
<br />
<br />
<input type="submit" value="let's go" disabled="disabled" />
</form>
Now I want to have a simple script to enable the submit when the values of the text boxes are not an empty string or null...
So I have something like this.. which I will bind to the window.onload
function enableButton(){
var formitemsArray = ['text1','text2','text3','text4'],
i;
// Loop through all items
for(i=0;i<formitemsArray.length;i++){
// validate the length on the keypress...
formitemsArray.onkeypress = function(){
// loop through all the items again
for(j=0;j<formitemsArray.length;j++){
if(formitemsArray[j] == "" || formitemsArray[j] == null ){
// return false or something???
}else{
document.getElementById("submitButton").disabled = false;
}
}
}
}
}
Now I think I'm on the right lines to a solution but I'm getting lost when trying to make sure that all the items are greater than a zero length string as I'm returning false too soon. Can someone set me straight please?
Welcome to event bubbling!
This does the following: listen to an event (onkeypress) on the whole element and all its children! Which means you can do the following:
document.getElementById('form-id').onkeypress = function(e) {
var text1 = document.getElementById('text1'),
text2 = document.getElementById('text2'),
text3 = document.getElementById('text3'),
text4 = document.getElementById('text4')
if (text1.value.length > 0 &&
text2.value.length > 0 &&
text3.value.length > 0 &&
text4.value.length > 0) {
document.getElementById('submit-button').disabled = false
}
// As an aside, for later: if you want to get the element
// that triggered the event, you have to do the following
// to be cross-browser:
var evt = e || window.event, // IE doesn't get the event passed by argument
target = e.target || e.srcElement // 'target' is official, old versions of FF used 'srcElement'
// With the 'target' variable, you can now play.
}
There is another more generic solution, but it might not fit your needs (note that it requires a forEach shim:
// Declare a counter variable
var count = 0
document.getElementById('form-id').onkeypress = function(e) {
// Get all the inputs!
var inputs = this.getElementsByTagName('input')
// Now loop through all those inputs
// Since a NodeList doesn't have the forEach method, let's borrow it from an array!
[].forEach.call(inputs, loopThroughInputs)
}
function loopThroughInputs(input) {
// First check the type of the input
if (input.type === 'text') {
// If the value is correct, increase the counter
if (input.value.length > 0) {
count++
}
// If the 4 inputs have increased the counter, it's alright!
if (count === 4) {
document.getElementById('submit-button').disabled = false
}
}
}
And now this code was proposed by #Esailija, and it is way better and cleaner. However, it also requires ES5-Shim (for the every method):
document.getElementById('form-id').onkeypress = function(e) {
var inputs = [].slice.call( this.querySelectorAll( '[type=text]') );
document.getElementById('submit-button').disabled = !inputs.every(function(input){
return !!input.value;
});
}
(This guy is brillant, just don't tell him)
There are a few ways you can do this... One would be to keep the button enabled but use javascript to check the validity of the form data upon submission. The benefit to this is that the validation code is only run once, when the user clicks submit and is expecting his data to be validated (at least I do) .
function validateForm() {
var formElement = document.forms[0]; // you didn't give me a name
for(var i = 0, l = formElement.elements.length; i < l; i++ ) {
if( formElement.elements[i].value.length === 0 ) {
return false;
}
return true;
}
}
The other way is live validation, which would validate each input onBlur (focus lost). This method has the benefit of showing the user in real time what values are bad, however this can be very resource heavy depending on the number of form elements and the way you introduce the check.
Personally I would go with my first suggestion; however with that said if you choose to validate each element, I would do so like this:
var formElement = document.forms[0]; // you didn't give me a name
for(var i = 0, l = formElement.elements.length; i < l; i++ ) {
formElement.elements[i].addEventListener('blur', function() {
if( this.value.length === 0 ) {
alert('this input is invalid');
}
}, false);
}
The latter method also requires you hold onto a 'state' variable to determine whether or not the form is valid upon submission, or check all the values again.
Hope this sheds some light, and I hope my code examples help some.
If possible use jquery validation plugin instead of re-inventing the code, http://docs.jquery.com/Plugins/Validation its so easy to use.
In this jsfiddle you'll find a way to monitor the progress of form contents. If all the field conditions are fulfilled, a submit button is shown. Maybe it's useful for you. Bare in mind that client side checking of a form may be tampered with, so you always need a server side check too, if your data need to adhere to certain requirements. In other words: client side form checks are merely usability enhancements.

In JavaScript, how do I detect whether or not the input contains letters?

My code is below, it outputs what the user is typing in the text box. It should output an error message if the user puts anything other than a number. I'm confused as to how to do this, though. Quite frankly, I'd settle with it being able to detect whether or not the first letter of input is a B, but I can't quite figure that out either and the former option is preferred.
HTML
<label for="bannerID">Banner ID: B</label><input type="text" name="bannerID" id="bannerID" onkeyup="showBannerID()" value="" /><br />
<p id="bannerOutput"></p>
JavaScript
function showBannerID() {
var textInput = document.getElementById('bannerID').value;
if (textInput.length == 0) {
document.getElementById('bannerOutput').innerHTML = "<strong class=\"error\">Field can't be empty!</strong>";
}
else if (textInput.charAt(0) == "B") {
document.getElementById('bannerOutput').innerHTML = "<strong class=\"error\">Please omit the B! It's not necessary.</strong>
}
else {
document.getElementById('bannerOutput').innerHTML = "Your Banner ID is: <strong>B" + textInput + "</strong>.";
}
}
You can use regular expressions to search for anything other than numbers:
if (/[^\d]/.test(textInput)) {
/* error stuff */
}
You can use isNaN() (Not a Number) as a condition.
isNaN(123) would give false, isNaN("hello") would give true.

Categories