I am fairly new. I am creating a webpage that ask a user for their ID. I want it to be a required field and only allow numbers. I appreciate if you lead me in the correct direction. this is what I have so far.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Search</title>
</head>
<body>
<div>
<table align="center">
<tr>
<td class="label">
Enter ID:
</td>
<td>
<input type="text" name="UserId" id="UserId" />
</td>
</tr>
</table>
</div>
</body>
</html>
This question is related to
html
asp.net-mvc-3
input
Try this with the + after [0-9]:
input type="text" pattern="[0-9]+" title="number only"
Of course, you can't fully rely on the client-side (javascript) validation, but that's not a reason to avoid it completely. With or without it, you have to do the server-side validation anyway (since the client can disable javascript). And that's just what you're left with, due to your non-javascript solution constraint.
So, after a submit, if the field value doesn't pass the server-side validation, the client should end up on the very same page, with additional error message specifying the requested value format. You also should provide the value format information beforehands, e.g. as a tool-tip hint (title
attribute).
There's most certainly no passive client-side validation mechanism existing in HTML 4 / XHTML.
On the other hand, in HTML 5 you have two options:
input of type number
:
<input type="number" min="xxx" max="yyy" title="Format: 3 digits" />
– only validates the range – if user enters a non-number, an empty value is submitted
– the field visual is enhanced with increment / decrement controls (browser dependent)
the pattern
attribute:
<input type="text" pattern="[0-9]{3}" title="Format: 3 digits" />
<input type="text" pattern="\d{3}" title="Format: 3 digits" />
– this gives you a full contorl over the format (anything you can specify by regular expression)
– no visual difference / enhancement
But here you still rely on browser capabilities, so do a server-side validation in either case.
Source: Stackoverflow.com