I am able to restrict user from typing special characters in the textbox but I need help on setting this restriction also when user is pasting special characters. How do I do this in this code of line?:
@Html.TextBoxFor(model => model.GroupName, new { @class ="form-control", @required="required", onkeypress="return /[0-9a-zA-Z ]/i.test(event.key);"})
CodePudding user response:
Consider a combination of a validation pattern and triggering validation on input
<input type="text" value="Test" pattern="[0-9a-zA-Z ]*" oninput="this.reportValidity()" title="Alphanumeric and space only!">
This doesn't prevent the user from inserting wrong characters, but it will immediately display a hint when wrong content was inserted.
Anyway, you always need to re-validate the input server-side, no matter what you do on client side.
CodePudding user response:
suppose that you have an Input
<input id="textInput" name="textInput">
and you have the following script to validate the copy:
$(function(){
$( "#textInput" ).bind( 'paste',function()
{
setTimeout(function()
{
//get the value of the input text
var data= $( '#textInput' ).val() ;
//replace the special characters to ''
var dataFull = data.replace(/[^\w\s]/gi, '');
//set the new value of the input text without special characters
$( '#textInput' ).val(dataFull);
});
});
});