Nov 19

You can specify a schema for validation when configuring the DocumentBuilderFactory that is used to parse the XML

static final String JAXP_SCHEMA_LANGUAGE =
    "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA =
    "http://www.w3.org/2001/XMLSchema";

DocumentBuilderFactory factory = 
   DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);

DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(url.openStream()); 

written by objects \\ tags: , , , , ,

Sep 30

Use the parse() method of the SimpleDateFormat class, it will throw an exception if the string does not contain a valid date. Use setLenient(false) to force strict parsing.


DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
dateFormat.setLenient(false);
try
{
   Date d = dateFormat.parse("01/05/06");

   // string contains valid date
}
catch (ParseException ex)
{
   // string contains invalid date
}

try
{
   Date d = dateFormat.parse("99/88/06");

   // string contains valid date
}
catch (ParseException ex)
{
   // string contains invalid date
} 

written by objects \\ tags: ,

Sep 08

Use static method Integer.parseInt() and catch the exception that is thrown when the number cannot be parsed.

String s = "123";
boolean isValidInteger = false;
try
{
   int i = Integer.parseInt(s);

   // s is a valid integer

   isValidInteger = true;
}
catch (NumberFormatException ex)
{
   // s is not an integer
}

written by objects \\ tags: , ,